package com.example.demo.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.Dto.LoginDto;
import com.example.demo.Dto.RegisterDto;
import com.example.demo.Service.UserService;
import com.example.demo.Util.ThreadLocallUtil;
import com.example.demo.VO.LoginVo;
import com.example.demo.VO.RegisterVo;
import com.example.demo.po.User;
import com.example.demo.result.ResponseResult;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;

@RestController
@RequestMapping("/api/v1/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户注册
     * @param registerDto
     * @return
     */
    @PostMapping("/register")
    public ResponseResult  register(@RequestBody RegisterDto registerDto) throws RuntimeException {
        // 字符串去掉左侧右侧空格
        String password = registerDto.getPassword().trim();
        String confirmPassword = registerDto.getConfirmPassword().trim();

        // 检验密码是否符合规则
        if (!password.equals(confirmPassword)) {
            throw new RuntimeException("两次密码不一致");
        }
        if (password.length() < 8) {
            throw new RuntimeException("密码的长度至少为8位！");
        }
         QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        QueryWrapper<User> email = queryWrapper.eq("email", registerDto.getEmail());
        User one = userService.getOne(email);
        // 查询该邮箱是否注册过账号
        if (one != null){
            return new ResponseResult().error(400,"该邮箱已注册！");
        }

        RegisterVo register = userService.register(registerDto);
        return new ResponseResult().ok(register);
    }
    /**
     * 用户登录
     */
    @PostMapping("/login")
 public ResponseResult login(@RequestBody LoginDto loginDto){
        LoginVo login = userService.login(loginDto);
        if (login==null){
            return new ResponseResult().error(400,"用户名或密码错误");
        }
        return new ResponseResult().ok(login);
 }

    /**
     *  刷新访问令牌
     * @param refreshToken
     * @return
     */
 @PutMapping("/refresh")
 public ResponseResult refresh(@RequestHeader("Refresh-Token") String refreshToken){
        if (refreshToken==null){
            return new ResponseResult().error(400,"请重新登录");
        }
     LoginVo refresh = userService.refresh(refreshToken);
        if (refresh==null){
            return new ResponseResult().error(400,"请重新登录");
        }
     return new ResponseResult().ok(refresh);
 }
 /**
     * 用户登出
     * @return
     */
@PostMapping("/logout")
    public ResponseResult logout(){
    ThreadLocallUtil.remove();
        return new ResponseResult().ok();
    }
}
